"""代码生成验证命令模块"""

import argparse
from pathlib import Path
import difflib
from datetime import datetime
from src.core.command import Command
from src.base.registry import bera
from src.core.common.template_engine import generate

class GenCodeCheckCommand(Command):
    """代码生成验证命令"""

    def __init__(self):
        super().__init__()
        self.name = "gen-code-check"
        self.group = "代码生成"
        self.help = "验证代码生成结果"
        self.description = """
        验证代码生成结果。该命令会:
        1. 读取meta.auto.json和template.j2文件
        2. 使用配置渲染模板生成临时文件
        3. 将生成的文件与target文件进行比对
        4. 输出比对结果
        5. 生成差异文件
        """

    def add_arguments(self, parser: argparse.ArgumentParser) -> None:
        """添加命令参数"""
        parser.add_argument('--directory', '-d',
                          default='assets/gen-code-check/AddOrEdit',
                          help='测试用例目录路径')

    def execute(self, args: argparse.Namespace) -> None:
        """执行命令"""
        try:
            bera.logger.info("开始执行gen-code-check命令")

            # 1. 确保目录存在
            test_dir = Path(args.directory)
            if not test_dir.exists():
                raise FileNotFoundError(f"错误: 测试目录 {args.directory} 不存在")

            meta_file = test_dir / 'meta.auto.json'
            template_file = test_dir / 'template.j2'

            # 查找target文件
            target_files = list(test_dir.glob('target.*'))
            if not target_files:
                raise FileNotFoundError("错误: 未找到target文件")
            target_file = target_files[0]  # 使用找到的第一个target文件
            target_ext = target_file.suffix  # 获取文件扩展名

            # 检查必要文件是否存在
            if not all(f.exists() for f in [meta_file, template_file, target_file]):
                raise FileNotFoundError(f"错误: 缺少必要的测试文件 (meta.auto.json, template.j2, {target_file.name})")

            # 2. 创建临时文件目录
            artifacts_dir = Path('artifacts/gen-code-check') / test_dir.name
            artifacts_dir.mkdir(parents=True, exist_ok=True)
            generated_file = artifacts_dir / f'generated{target_ext}'

            # 3. 使用生成器接口生成文件
            try:
                generate(
                    template_file_path=str(template_file),
                    target_abs_path=str(generated_file),
                    meta_file_path=str(meta_file)
                )
            except Exception as e:
                raise Exception(f"错误: 生成文件失败 - {str(e)}")

            # 4. 比对结果
            with open(target_file, 'r', encoding='utf-8') as f1, \
                 open(generated_file, 'r', encoding='utf-8') as f2:
                file1_lines = f1.readlines()
                file2_lines = f2.readlines()

            diff = list(difflib.unified_diff(
                file1_lines,
                file2_lines,
                fromfile=str(target_file),
                tofile=str(generated_file),
                lineterm=''
            ))

            # 生成带时间戳的差异文件
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            diff_file = artifacts_dir / f'diff.{timestamp}.txt'

            with open(diff_file, 'w', encoding='utf-8') as f:
                f.write('\n'.join(diff))

            bera.logger.info(f"差异文件已生成: {diff_file}")

            if len(diff) == 0:
                bera.logger.info("✅ 验证通过: 生成的文件与目标文件完全一致")
            else:
                bera.logger.error("❌ 验证失败: 发现差异")
                for line in diff:
                    bera.logger.error(line)
                raise Exception("验证失败: 生成的文件与目标文件不一致")

            bera.logger.info("gen-code-check命令执行完成")

        except Exception as e:
            if args.verbose:
                import traceback
                traceback.print_exc()
            raise